package cuong.ptit.androidvn;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import cuong.ptit.andoridvn.R;
import cuong.ptit.androidvn.helper.Function;
import cuong.ptit.androidvn.helper.JSONParser;
import cuong.ptit.androidvn.helper.SmartToast;
import cuong.ptit.androidvn.widget.PullAndLoadListView;
import cuong.ptit.androidvn.widget.PullAndLoadListView.OnLoadMoreListener;
import cuong.ptit.androidvn.widget.PullToRefreshListView.OnRefreshListener;

public class ListCategory extends ListActivity {

	private ProgressDialog pDialog;
	private int countLoadmore = 10;
	private int in = 0;
	// create JSON Parser
	JSONParser jsonParser = new JSONParser();

	// listArray to lisview
	ArrayList<HashMap<String, String>> categoryList;

	ArrayList<HashMap<String, String>> categoryListLoad;

	// get url JSON
	// private static final String url =
	// "http://android.vn/api.php?action=getthreads&hash=d8e8fca2dc0f896fd7cb4cb0031ba249&node_id=8";
	private static final String url = "http://android.vn/api.php?action=getThreads&hash=d8e8fca2dc0f896fd7cb4cb0031ba249&order_by=last_post_date&order=desc&node_id=8";
	private static final String TAG_TITLE = "title";
	private static final String TAG_ID = "thread_id";
	private static final String TAG_DATE = "last_post_date";

	// name nodes category
	/*
	 * private static final String TAG_NOTES_ID = "nodes_id"; private static
	 * final String TAG_TITLE = "title"; private static final String
	 * TAG_DESCRIPTION = "description"; private static final String
	 * TAG_DISPLAY_ORDER = "display_order";
	 */

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_category);

		categoryList = new ArrayList<HashMap<String, String>>();

		// load category in background
		new LoadCategory().execute();

		// set Onclick item lisview

		/*
		 * ListView lv = getListView();
		 * 
		 * lv.setOnItemClickListener(new OnItemClickListener() {
		 * 
		 * @Override public void onItemClick(AdapterView<?> arg0, View view, int
		 * arg2, long arg3) {
		 * 
		 * Intent i = new Intent(getApplicationContext(), ListThread.class);
		 * 
		 * String node_id = ((TextView) findViewById(R.id.id_category))
		 * .getText().toString(); i.putExtra("node_id", node_id);
		 * 
		 * startActivity(i); } });
		 */

		// pull refresh list view

		((PullAndLoadListView) getListView())
				.setOnRefreshListener(new OnRefreshListener() {

					@Override
					public void onRefresh() {

						new PullRefreshList().execute();
					}
				});

		// load more list view

		((PullAndLoadListView) getListView())
				.setOnLoadMoreListener(new OnLoadMoreListener() {

					@Override
					public void onLoadMore() {

						countLoadmore = countLoadmore + 10;
						in = categoryList.size();
						new LoadMoreDataList().execute();

					}

				});

	}

	// pull refresh listview

	class PullRefreshList extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {

			if (isCancelled()) {
				return null;
			}

			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
			}

			categoryList.clear();
			// refresh data
			// get json item
			List<NameValuePair> paramss = new ArrayList<NameValuePair>();
			String json = jsonParser.makeHttpRequest(url, "GET", paramss);

			try {
				JSONObject threadnews = new JSONObject(json);
				JSONObject thread = threadnews.getJSONObject("threads");

				Iterator<?> keys = thread.keys();
				while (keys.hasNext()) {
					String key = (String) keys.next();

					JSONObject c = thread.getJSONObject(key);
					String id = c.getString(TAG_ID);
					String tiele = c.getString(TAG_TITLE);

					HashMap<String, String> map = new HashMap<String, String>();

					map.put(TAG_ID, id);
					map.put(TAG_TITLE, tiele);

					categoryList.add(map);

				}

			} catch (JSONException e) {
				e.printStackTrace();
			}

			Function.CollectionSort(categoryList, "thread_id");

			countLoadmore = 10;
			in = 10;

			Log.d("category", ":" + categoryList);

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {

			((BaseAdapter) getListAdapter()).notifyDataSetChanged();
			((PullAndLoadListView) getListView()).onRefreshComplete();
			super.onPostExecute(result);
		}

		@Override
		protected void onCancelled() {
			((PullAndLoadListView) getListView()).onRefreshComplete();
			super.onCancelled();
		}

	}

	// load more listview
	class LoadMoreDataList extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {

			if (isCancelled()) {
				return null;
			}

			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {

			}
			// load json new here------------------------

			String strlimit = String.valueOf(countLoadmore);

			// get json limit new
			List<NameValuePair> paramsLoad = new ArrayList<NameValuePair>();
			paramsLoad.add(new BasicNameValuePair("limit", strlimit));
			String jsonNew = jsonParser.makeHttpRequest(url, "GET", paramsLoad);

			// get json new limit 20
			List<NameValuePair> paramsLoad1 = new ArrayList<NameValuePair>();
			paramsLoad1.add(new BasicNameValuePair("limit", String
					.valueOf(countLoadmore + 20)));
			String jsonNew1 = jsonParser.makeHttpRequest(url, "GET",
					paramsLoad1);

			categoryListLoad = new ArrayList<HashMap<String, String>>();
			try {
				JSONObject j = new JSONObject(jsonNew);
				JSONObject jnew = j.getJSONObject("threads");

				Iterator<?> keys = jnew.keys();
				while (keys.hasNext()) {
					String key = (String) keys.next();

					JSONObject thread = jnew.getJSONObject(key);

					String thread_id = thread.getString("thread_id");
					String title = thread.getString("title");

					HashMap<String, String> map = new HashMap<String, String>();
					map.put(TAG_ID, thread_id);
					map.put(TAG_TITLE, title);
					// map.put(TAG_ID, title);

					categoryListLoad.add(map);

				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			// add new item in new arraylist

			Function.CollectionSort(categoryListLoad, "thread_id");
			Log.d("CategoryLoad", ">:" + categoryListLoad);
			Log.d("Category1", ">:" + categoryList);

			if (jsonNew.length() < jsonNew1.length()) {
				for (int ab = in; ab < categoryListLoad.size(); ab++) {
					HashMap<String, String> a = categoryListLoad.get(ab);
					categoryList.add(a);
				}
			}

			Log.d("Category2", ">:" + categoryList);
			Function.CollectionSort(categoryList, "thread_id");

			Log.d("new", "load = " + categoryListLoad.size() + "thread = "
					+ categoryList.size() + "in=" + in);
			// Log.d("string", ">" + categoryListLoad);

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);

			((BaseAdapter) getListAdapter()).notifyDataSetChanged();
			((PullAndLoadListView) getListView()).onLoadMoreComplete();
		}

		@Override
		protected void onCancelled() {
			((PullAndLoadListView) getListView()).onLoadMoreComplete();
		}

	}

	// load listview
	class LoadCategory extends AsyncTask<String, String, String> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(ListCategory.this);
			pDialog.setMessage("Loading thread.....");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected String doInBackground(String... args) {

			// load json
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			String json = jsonParser.makeHttpRequest(url, "GET", params);

			try {
				// convert string to json
				JSONObject categorys = new JSONObject(json);
				// to object nodes
				JSONObject category = categorys.getJSONObject("threads");

				Iterator<?> keys = category.keys();

				while (keys.hasNext()) {
					// create string save key
					String key = (String) keys.next();
					JSONObject cates = category.getJSONObject(key);

					String thread_id = cates.getString("thread_id");
					String title = cates.getString(TAG_TITLE);
					String date = cates.getString(TAG_DATE);
					/*
					 * String description = cates.getString(TAG_DESCRIPTION);
					 * String order_by = cates.getString(TAG_DISPLAY_ORDER);
					 */

					HashMap<String, String> map = new HashMap<String, String>();

					map.put(TAG_ID, thread_id);
					map.put(TAG_TITLE, title);
					map.put(TAG_DATE, date);
					/*
					 * map.put(TAG_NOTES_ID, node_id); map.put(TAG_TITLE,
					 * title); map.put(TAG_DESCRIPTION, description);
					 * map.put(TAG_DISPLAY_ORDER, order_by);
					 */
					categoryList.add(map);

				}

			} catch (JSONException e) {
				e.printStackTrace();
			}

			Function.CollectionSortBA(categoryList, "last_post_date");
			Log.d("category", ":" + categoryList);
			return null;
		}

		@Override
		protected void onPostExecute(String file_url) {
			pDialog.dismiss();

			runOnUiThread(new Runnable() {

				// sort ArrayList of Hashmap

				@Override
				public void run() {
					ListAdapter adapter = new SimpleAdapter(ListCategory.this,
							categoryList, R.layout.list_item_category,
							new String[] { TAG_TITLE },
							new int[] { R.id.title_category });
					setListAdapter(adapter);

				}

			});

		}

	}
}
